/**
  微信参数设置
*/

package setting

import (
	"code.gitea.io/gitea/modules/log"
	"github.com/ArtisanCloud/PowerWeChat/v3/src/kernel"
	wechat_sdk "github.com/ArtisanCloud/PowerWeChat/v3/src/officialAccount"
)

var Wechat = struct {
	Enabled             bool
	DefaultDomainName   string
	UserConfig          WechatUserConfigType
	TempQrExpireSeconds int
	SDK                 *wechat_sdk.OfficialAccount
	cache               kernel.CacheInterface

	// 注册过期时间
	RegisterationExpireSeconds int
}{}

type WechatUserConfigType struct {
	AppID         string
	AppSecret     string
	RedisAddr     string
	MessageToken  string
	MessageAesKey string
}

// loadWechatSettingsFrom
/**
 * 创建PowerWechat全局工具类实例
 * 配置文件： custom/conf/app.ini
 */
func loadWechatSettingsFrom(rootCfg ConfigProvider) {
	sec := rootCfg.Section("wechat")
	Wechat.Enabled = sec.Key("ENABLED_WECHAT_QR_SIGNIN").MustBool(true)
	log.Info("ENABLED_WECHAT_QR_SIGNIN == '%b'", Wechat.Enabled)
	Wechat.DefaultDomainName = sec.Key("WECHAT_QR_SERVICE_DOMAIN_NAME").MustString("devstar.cn")

	Wechat.UserConfig.AppID = sec.Key("WECHAT_APP_ID").MustString("")
	Wechat.UserConfig.AppSecret = sec.Key("WECHAT_APP_SECRET").MustString("")
	Wechat.UserConfig.RedisAddr = sec.Key("WECHAT_REDIS_ADDR").MustString("")
	Wechat.UserConfig.MessageToken = sec.Key("WECHAT_MESSAGE_TOKEN").MustString("")
	Wechat.UserConfig.MessageAesKey = sec.Key("WECHAT_MESSAGE_AES_KEY").MustString("")
	if Wechat.UserConfig.AppID != "" && Wechat.UserConfig.AppSecret != "" {
		log.Info("createPowerWechatApp AppID:%s ", Wechat.UserConfig.AppID)
		createPowerWechatApp(Wechat.UserConfig)
	}

	Wechat.TempQrExpireSeconds = sec.Key("WECHAT_TEMP_QR_EXPIRE_SECONDS").MustInt(60)
	// 扫码后，最长注册时间：默认24小时
	Wechat.RegisterationExpireSeconds = sec.Key("WECHAT_REGISTERATION_EXPIRE_SECONDS").MustInt(86400)
}

/**
 * 创建微信公众号工具类
 *
 * @param userConfig 微信公众号配置信息, 详见 `custom/conf/app.ini`
 * @return PowerWechat app 实例.
 */
func createPowerWechatApp(userConfig WechatUserConfigType) {

	if userConfig.RedisAddr != "" {
		Wechat.cache = kernel.NewRedisClient(&kernel.UniversalOptions{
			Addrs: []string{userConfig.RedisAddr},
		})
	}

	var err error

	Wechat.SDK, err = wechat_sdk.NewOfficialAccount(&wechat_sdk.UserConfig{

		AppID:  userConfig.AppID,
		Secret: userConfig.AppSecret,

		Token:  userConfig.MessageToken,
		AESKey: userConfig.MessageAesKey,

		Log: wechat_sdk.Log{
			Level: "error",
			File:  "./wechat-error.log",
		},

		HttpDebug: false,
		Debug:     false,
		Cache:     Wechat.cache,
		// Sandbox:   true,
	})
	if err != nil {
		log.Warn("创建微信工具类 PowerWechat 失败，请检查 modules/setting/wechat.go ")
	}
}
